<template>
  <div id="login-container">
    <div class="login-left">
      <div>
        <img src="../../assets/logo.png" alt="" />
        <p style="font-size: 50px; color: #fff">药典目录管理</p>
      </div>
    </div>
    <div class="login-right">
      <div class="login-main">
        <h4 class="login-title">请登录您的账号</h4>
        <form class="login-form" @submit.prevent="onSubmit">
          <dx-form
            :form-data="formData"
            :disabled="loading"
            @field-data-changed="onFieldDataChanged"
          >
            <dx-item
              data-field="passId"
              editor-type="dxTextBox"
              :editor-options="{
                stylingMode: 'outlined',
                placeholder: '请输入账号',
                mode: 'passId',
                inputAttr: { class: 'login-input' },
              }"
            >
              <dx-required-rule message="请输入账号" />
              <dx-pattern-rule
                :pattern="accountPattern"
                message="用户名应为4到16位（字母，数字，下划线，减号）"
              />
              <dx-label :visible="false" />
            </dx-item>

            <dx-item
              data-field="passWord"
              editor-type="dxTextBox"
              :editor-options="{
                stylingMode: 'outlined',
                placeholder: '请输入密码',
                mode: 'password',
              }"
            >
              <dx-required-rule message="请输入密码" />
              <dx-label :visible="false" />
            </dx-item>
            <dx-item template="verCode"></dx-item>
            <template #verCode>
              <DxBox direction="row" width="100%">
                <DxItem :ratio="0" base-size="100%">
                  <DxTextBox
                    placeholder="请输入验证码"
                    v-model="formData.verCode"
                    stylingMode="outlined"
                  >
                  </DxTextBox>
                </DxItem>
                <DxItem :ratio="0" :base-size="100">
                  <div>
                    <img
                      :src="verCodeImageUrl"
                      style="
                        height: 30px;
                        width: 100%;
                        margin: auto;
                        cursor: pointer;
                      "
                      v-on:click="imageClick"
                    />
                  </div>
                </DxItem>
              </DxBox>
            </template>
            <dx-button-item>
              <dx-button-options
                :element-attr="{ class: 'submit-button' }"
                width="100%"
                type="default"
                :use-submit-behavior="true"
              >
                登录
              </dx-button-options>
            </dx-button-item>
            <dx-item data-field="login-type" template="login">
              <dx-label :visible="false" />
            </dx-item>
            <template #login>
              <div class="login-type">
                <DxButton
                  text="账号密码登录"
                  stylingMode="text"
                  type="default"
                  :disabled="true"
                />
                <DxButton
                  text="手机号登录"
                  stylingMode="text"
                  type="default"
                  @click="goPhone()"
                />
              </div>
            </template>
          </dx-form>
        </form>
      </div>
    </div>
  </div>
  <DxPopup
    v-model:visible="popupVisible"
    :drag-enabled="false"
    :close-on-outside-click="true"
    :show-title="false"
    :width="300"
    :height="130"
    title="选择诊所"
  >
    <div
      style="
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 100%;
      "
    >
      <div>
        <DxSelectBox
          :data-source="tenantIds"
          placeholder="选择诊所"
          value-expr="key"
          display-expr="value"
          v-model:value="formData.tenantId"
          style="margin: auto"
        />
      </div>
      <div style="margin-top: 15px">
        <DxButton
          :width="120"
          text="确定"
          type="default"
          styling-mode="outlined"
          @click="trueForm"
        />
      </div>
    </div>
  </DxPopup>
</template>

<script lang='ts'>
import DxLoadIndicator from "devextreme-vue/load-indicator";
import { DxBox } from "devextreme-vue/box";
import { DxTextBox } from "devextreme-vue/text-box";
import { DxButton } from "devextreme-vue/button";
import { DxSelectBox } from "devextreme-vue/select-box";
import { DxPopup } from "devextreme-vue/popup";
import DxForm, {
  DxItem,
  DxRequiredRule,
  DxLabel,
  DxButtonItem,
  DxButtonOptions,
  DxPatternRule,
} from "devextreme-vue/form";
import { Options, Vue } from "vue-class-component";
import { ApiTool } from "@/api/api-tool";
import { Inject } from "vue-property-decorator/lib";
import { ViewTool } from "@/utils/view-tool";
import { ApiExceptionShow } from "@/utils/api-exception-show";
import { Tool } from "../../utils/tool";
import { SearchByURL } from "@/utils/search-byurl";
import { authClient, AuthInfoI } from "@/api/api_auth";
import { Auth } from "@/utils/auth";
import config from "@/config/config";
const { authOptions } = config;

interface SelectInfo {
  key: string;
  value: string;
}

@Options({
  components: {
    DxLoadIndicator,
    DxForm,
    DxBox,
    DxPatternRule,
    DxRequiredRule,
    DxItem,
    DxLabel,
    DxButtonItem,
    DxButtonOptions,
    DxTextBox,
    DxPopup,
    DxSelectBox,
    DxButton,
  },
})
export default class AccountLogin extends Vue {
  accountPattern = /^[a-zA-Z0-9_-]{4,16}$/;
  @Inject()
  apiTool: ApiTool;
  searchByURL: SearchByURL;
  formData = {
    passId: "",
    passWord: "",
    tenantId: "",
    verCode: "",
  };

  loading = false;

  /** 弹框显示 */
  popupVisible = false;

  tenantIds: SelectInfo[] = [];

  /** 获取图片验证码路径 */
  verCodeImageUrl = "";

  private refreshVerCode() {
    this.verCodeImageUrl = `${
      this.apiTool.url
    }/Index/Login/VerImage?${Math.random()}`;
  }

  imageClick() {
    this.refreshVerCode();
  }

  mounted() {
    this.refreshVerCode();
  }
  created() {
    this.searchByURL = new SearchByURL(this.$router, 1);
  }
  goPhone() {
    this.searchByURL.setParamsToUrl({ type: "phone" });
  }
  trueForm() {
    ViewTool.showLoading(true, this);
    this.loginForJump()
      .then(() => {
        ViewTool.showLoading(false, this);
      })
      .catch((error) => {
        ApiExceptionShow.showException(error, this);
      });
  }

  private async loginForJump() {
    let client = this.apiTool.createAuthClient(authClient);
    let form: AuthInfoI = {
      ...authOptions,
      grant_type: "password",
      username: this.formData.passId,
      password: this.formData.passWord,
    };
    await client.login(form).then((result) => {
      let token = result["access_token"];
      Auth.saveToken(token);
      Auth.saveUser(result);
    });

    // this.apiTool.loadToken();
    this.$router.push("/");
  }

  private async login() {
    this.loginForJump();
  }

  onSubmit() {
    //显示loading框
    ViewTool.showLoading(true, this);
    this.login()
      .then(() => {
        ViewTool.showLoading(false, this);
      })
      .catch((error) => {
        ApiExceptionShow.showException(error, this);
      });
  }

  ///监听更高
  onFieldDataChanged(e) {
    if (e.dataField === "passId") {
      // this.onGetTenantId(e.value);
    }
  }
}
</script>
<style src="./account.scss" lang="scss" scoped></style>
<style lang="scss">
.login-form {
  .dx-placeholder,
  .dx-texteditor-input {
    font-size: 16px;
  }
  .dx-button {
    height: 50px;
    font-size: 16px;
  }
}
</style>
